//
//  PersonnelDetailsViewController.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/9/14.
//

#import "PersonnelDetailsViewController.h"
#import "PersonnelModel.h"
#import "PersonnelDetailsTableViewCell.h"
#import "AppendDetailsModel.h"
#import "WarnModel.h"
#import "AppendLogsableViewCell.h"
#import "foundQuestModel.h"
#import "AppendLogsModel.h"
#import "TimeFrameShowView.h"
#import "UIScrollView+EmptyDataSet.h"
#import "foundQuestViewController.h"
#import "SYAudio.h"
#import "UserQuestViewController.h"
#import "GRefreshAutoNormalFooter.h"
#import "DTChoosePersonListShowView.h"
#import "YTSelectStringShowView.h"

@interface PersonnelDetailsViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property (nonatomic ,strong) PersonnelDetailsModel * model;

@property (nonatomic ,strong) UIButton * grbtn;
@property (nonatomic ,strong) UIButton * rzbtn;
@property (nonatomic ,strong) UIView * lineview;
@property (nonatomic ,strong) UITableView * rztableview;
@property (nonatomic ,strong) UIButton * upBtn;

@property (nonatomic ,strong) NSString * pondId;
@property (nonatomic ,strong) NSString * pondName;

@property (nonatomic ,strong) NSString * startTime;
@property (nonatomic ,strong) NSString * endTime;
@property (nonatomic ,strong) NSMutableArray<AppendLogsModel *> * modelArray;
@end

@implementation PersonnelDetailsViewController

-(NSMutableArray<AppendLogsModel *> *)modelArray{
    if(!_modelArray){
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
- (NSString *)startTime{
    if(!_startTime){
        _startTime = [NSDate br_stringFromDate:[[NSDate new] br_getNewDateToDays:-6] dateFormat:@"yyyy-MM-dd"];
    }
    return _startTime;
}
- (NSString *)endTime{
    if(!_endTime){
        _endTime = [NSDate br_stringFromDate:[NSDate new] dateFormat:@"yyyy-MM-dd"];
    }
    return _endTime;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.NoDataHidden = YES;
    [self setupView];
    // Do any additional setup after loading the view.
}
- (void)setupView{
    UIView * topview = [UIView new];
    topview.backgroundColor = KcolorHex(@"#0967FF");
    [self.view addSubview:topview];
    [topview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.offset(Knav_HeightX);
    }];
    MJWeakSelf
    UIView * backview = [UIView new].addClickBlock(^{
        [weakSelf popViewController];
    });
    [topview addSubview:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(44);
        make.left.bottom.offset(0);
        make.width.offset(kwt(120));
    }];
    
    UIImageView * leftimg = kimageView(@"white_path");
    [backview addSubview:leftimg];
    [leftimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(20);
        make.left.offset(kwt(10));
        make.centerY.offset(0);
    }];
    
    UILabel * leftlab = [DTKTool labelWithText:@"人员详情" andFont:kCFont(18) andTextColor:UIColor.whiteColor];
    [backview addSubview:leftlab];
    [leftlab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(43));
        make.centerY.offset(0);
    }];
    UIButton * zdspBtn = [UIButton buttonWithType:0];
    zdspBtn.addNormalText(@"新增任务").addNormalColor(UIColor.whiteColor).addFont(kCFont(18)).addTarget(self,@selector(addRW));
    [topview addSubview:zdspBtn];
    [zdspBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(kwt(-10));
        make.centerY.equalTo(leftlab);
    }];
    
    UIView * ssview = [UIView new];
    ssview.backgroundColor = KcolorHex(@"#F1F5FA");
    [self.view addSubview:ssview];
    [ssview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.right.offset(0);
        make.height.offset(kwt(48));
        make.top.equalTo(topview.mas_bottom);
    }];
    
    UIButton * grbtn = [UIButton buttonWithType:0];
    self.grbtn = grbtn;
    grbtn.addNormalText(@"个人信息").addNormalColor(KcolorHex(@"#222222")).addFont(kFont(16)).addTarget(self,@selector(grbtnclick));
    [ssview addSubview:grbtn];
    [grbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.offset(0);
        make.width.offset(kwt(106));
    }];
    UIButton * rzbtn = [UIButton buttonWithType:0];
    self.rzbtn = rzbtn;
    rzbtn.addNormalText(@"工作日志").addNormalColor(KcolorHex(@"#222222")).addFont(kFont(16)).addTarget(self,@selector(rzbtnclick));
    [ssview addSubview:rzbtn];
    [rzbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.offset(0);
        make.left.width.offset(kwt(106));
    }];
    
    UIView * lineview = [UIView new];
    self.lineview= lineview;
    lineview.backgroundColor =KcolorHex(@"#1983FA");
    [DTKTool YJ:kwt(1.5) andView:lineview];
    lineview.frame = CGRectMake(kwt(40), kwt(45), kwt(26), kwt(3));
    [ssview addSubview:lineview];
    
    
    [self.view addSubview:self.tableview];
    self.tableview.backgroundColor = KcolorHex(@"#ECEDEE");
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.offset(0);
        make.top.equalTo(ssview.mas_bottom);
    }];
    
    
    [self.view addSubview:self.rztableview];
    self.rztableview.hidden = YES;
    self.rztableview.backgroundColor = KcolorHex(@"#E6E9EE");
    [self.rztableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(ssview.mas_bottom);
    }];
    
    
    self.upBtn = [UIButton buttonWithType:0];
    [self.upBtn setBackgroundImage:[UIImage imageNamed:@"top"] forState:UIControlStateNormal];
    [self.upBtn addTarget:self action:@selector(upbtnclick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.upBtn];
    [self.upBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(kwt(-50)- KSafeAreaBottomHeight);
        make.right.offset(kwt(-20));
        make.width.height.offset(kwt(50));
    }];
    [self grbtnclick];

}
- (void)upbtnclick{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.rztableview scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
- (void)addRW{
    foundQuestViewController * vc = [foundQuestViewController new];
    PondUserModel * m = [PondUserModel new];
    m.userId = self.model.userId;
    m.phone = self.model.phone;
    m.realName = self.model.realName;
    m.userIdentity = self.model.userIdentity;
    vc.usermodel = m;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)grbtnclick{
    self.grbtn.addFont(kCFont(19));
    self.rzbtn.addFont(kFont(16));
    self.rztableview.hidden = YES;
    self.upBtn.hidden = YES;
    [self loadNewData];
    [[SYAudio shareAudio] audioStop];
    
    [UIView animateWithDuration:0.2 animations:^{
        self.lineview.mj_x = self.grbtn.mj_x + kwt(40);
    }];
}

- (UITableView *)rztableview{
    if(!_rztableview){
        _rztableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kwt(120), SCREEN_WIDTH, SCREEN_HEIGHT - kwt(120)) style:UITableViewStyleGrouped];
        _rztableview.delegate = self;
        _rztableview.dataSource = self;
        //        _tableview.backgroundColor =BgColor;
        _rztableview.emptyDataSetSource = self;
        _rztableview.emptyDataSetDelegate = self;
        _rztableview.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        if (@available(iOS 11.0, *)) {
            _rztableview.estimatedRowHeight = 0;
            _rztableview.estimatedSectionHeaderHeight = 0;
            _rztableview.estimatedSectionFooterHeight = 0;
            _rztableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _rztableview.sectionHeaderTopPadding = 0;
            _rztableview.fillerRowHeight = 0;
        }
        _rztableview.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _rztableview.sectionHeaderHeight = 0.01;
        _rztableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _rztableview.sectionFooterHeight = 0.01;
        _rztableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _rztableview.backgroundColor = UIColor.clearColor;
        _rztableview.clipsToBounds = YES;
        MJWeakSelf
        [self addFooterView:^{
            [weakSelf addMoreData];
        } andCount:0];
        [self addHeaderView:^{
            [weakSelf refreshingData];

        }];
     
    }
    return _rztableview;
}


-(void)refreshingData{
    self.pageNo = 1;
    [self.modelArray removeAllObjects];
    [self loadRZNewData];
}

-(void)addMoreData{
    self.pageNo += 1;
    [self loadRZNewData];
}

- (void)addFooterView:(MJRefreshComponentAction)Block andCount:(int)count {
    GRefreshAutoNormalFooter * footer = [GRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        Block();
    }];
    ///无感知刷新数量
    footer.triggerAutomaticallyRefreshPercent = count;
    self.rztableview.mj_footer = footer;
}
- (void)addHeaderView:(MJRefreshComponentAction)Block{
    self.rztableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        Block();
    }];
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{ return YES; }
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    //加入你自定义的view
    UIView * noView = [UIView new];
    UIView * NewnoView = [UIView new];
    //    NewnoView.backgroundColor = UIColor.whiteColor;
    [noView addSubview:NewnoView];
    [NewnoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(KSCREEN_WIDTH);
        make.center.offset(0);
        make.height.mas_offset(KSCREEN_HEIGHT);
    }];
    UIImageView * noImage = [UIImageView new];
    [noView addSubview:noImage];
    noImage.image = [UIImage imageNamed:@"no_data"];
    [noImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.centerY.mas_offset(-100);
    }];
    
    UILabel * noTitleLab = [UILabel new];
    [noView addSubview:noTitleLab];
    noTitleLab.text = @"暂无数据";
    noTitleLab.font = kCFont(17);
    noTitleLab.textColor = [UIColor colorWithHexString:@"#262626"];
    [noTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(noImage.mas_bottom).offset(30);
        make.centerX.mas_offset(0);
    }];
    
    return noView;
}
- (void)rzbtnclick{
    self.rzbtn.addFont(kCFont(19));
    self.grbtn.addFont(kFont(16));
    self.rztableview.hidden = NO;
    self.upBtn.hidden = NO;
    [self loadRZNewData];
    [UIView animateWithDuration:0.2 animations:^{
        self.lineview.mj_x = self.rzbtn.mj_x + kwt(40);
    }];
}
-(void)loadNewData{
    
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [SCNetManger PostAppAccountGetAppUserManageDetailWithID:self.userId andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        if(model.code == 200){
            self.model = [PersonnelDetailsModel yy_modelWithDictionary:model.result];
            [self.tableview reloadData];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}

- (void)loadRZNewData{
    
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:self.userId forKey:@"userId"];
    [dict setObject:self.startTime forKey:@"startTime"];
    //    [dict setObject:[NSString stringWithFormat:@"%@ 23:59:59",self.endTime] forKey:@"endTime"];
    [dict setObject:self.endTime forKey:@"endTime"];
    [dict setObject:self.pondId forKey:@"pondId"];
//    [dict setObject:@(self.pageNo) forKey:@"pageNo"];
//    [dict setObject:@(self.pageSize) forKey:@"pageSize"];
//    [dict setObject:@(5) forKey:@"pageSize"];
    if(self.modelArray.count > 0){
        [dict setObject:self.modelArray.lastObject.cardTime forKey:@"pageTime"];
    }
    [SCNetManger PostcardGetUserLogModelWithDict:dict andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        if(model.code == 200){
            NSArray * array = [NSArray yy_modelArrayWithClass:AppendLogsModel.class json:model.result];
            [self.modelArray addObjectsFromArray:array];
            if(array.count == 0 && self.modelArray.count > 0){
                [self.rztableview.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self.rztableview.mj_footer endRefreshing];
            }
        } else {
            [self.view showWarning:model.message];
        }
        [self.rztableview reloadData];
    }];
}



-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(tableView == self.rztableview){
        UIView * headerview = [UIView new];
        UIView * btnview = [UIView new];
        MJWeakSelf
        btnview.addClickBlock(^{
            [weakSelf openTime];
        });
        [headerview addSubview:btnview];
        btnview.backgroundColor= UIColor.whiteColor;
        [DTKTool YJ:kwt(4) andView:btnview];
        [btnview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.left.offset(kwt(10));
            make.width.offset(kwt(175));
            make.height.offset(kwt(31));
        }];
        UILabel * time = [DTKTool labelWithText:@"-" andFont:kFont(16) andTextColor:KcolorHex(@"#222222")];
        [btnview addSubview:time];
        [time mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.left.offset(kwt(11));
        }];
        
        UIImageView * img = kimageView(@"arrow_down");
        [btnview addSubview:img];
        [img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.right.offset(kwt(-11));
            make.width.offset(kwt(12));
            make.height.offset(kwt(7));
        }];
        
        time.text = [NSString stringWithFormat:@"%@-%@~%@-%@",[self.startTime componentsSeparatedByString:@"-"][1],[self.startTime componentsSeparatedByString:@"-"].lastObject,[self.endTime componentsSeparatedByString:@"-"][1],[self.endTime componentsSeparatedByString:@"-"].lastObject];
        
        
        UIView * tkbtnview = [UIView new];
        tkbtnview.addClickBlock(^{
            [weakSelf openTKBZ];
        });
        [headerview addSubview:tkbtnview];
        tkbtnview.backgroundColor= UIColor.whiteColor;
        [DTKTool YJ:kwt(4) andView:tkbtnview];
        [tkbtnview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.left.equalTo(btnview.mas_right).offset(kwt(8));
            make.right.offset(kwt(-8));
            make.height.offset(kwt(31));
        }];
        UILabel * pondname = [DTKTool labelWithText:(self.pondName.length > 0)?self.pondName:@"全部编组-全部池塘" andFont:kFont(15) andTextColor:KcolorHex(@"#222222")];
        [tkbtnview addSubview:pondname];
        [pondname mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.left.offset(kwt(8));
            make.right.offset(kwt(-35));
        }];
        
        UIImageView * tkimg = kimageView(@"arrow_down");
        [tkbtnview addSubview:tkimg];
        [tkimg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.right.offset(kwt(-11));
            make.width.offset(kwt(12));
            make.height.offset(kwt(7));
        }];
        
        return headerview;
    } else {
        return [UIView new];
    }
    
}
- (void)openTKBZ{
    ///选编组和池塘
    [self.view showBusyHUD];
    [SCNetManger PostPondTissueGetPondTissueListWithDict: [NSMutableDictionary dictionary] andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        if(model.code ==200){
            NSArray <getPondTissueListModel *>* array = [NSArray yy_modelArrayWithClass:getPondTissueListModel.class json:model.result ];
            NSLog(@"%@",array);
            MJWeakSelf
            [DTChoosePersonListShowView showViewWithArray:array andBlock:^(getPondTissueListModel * _Nonnull pondModel) {
                [weakSelf openTKWithtissueId:pondModel.ID andName:pondModel.TJname];
            } andCZBlock:^{
                    weakSelf.pondId = @"";
                    weakSelf.pondName =@"";
                    [weakSelf refreshingData];
            }];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}
- (void)openTKWithtissueId:(NSString *)tissueId andName:(NSString *)name{
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:tissueId forKey:@"tissueId"];
    [SCNetManger PostTaskPondListWithDict:dict  andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        if(model.code ==200){
            NSArray <getPondTissueListModel *>* array = [NSArray yy_modelArrayWithClass:getPondTissueListModel.class json:model.result ];
            MJWeakSelf
            NSMutableArray * nameArray = [NSMutableArray array];
            for (getPondTissueListModel * tkmodel in array) {
                [nameArray addObject:tkmodel.name];
            }
            [YTSearchStringShowView showViewWithTitle:@"池塘名称" andDateArray:nameArray andBlock:^(NSString * _Nonnull str) {
                for (getPondTissueListModel * tkmodel in array) {
                    if([tkmodel.name isEqualToString:str]){
                        weakSelf.pondId = tkmodel.ID;
                        weakSelf.pondName = [NSString stringWithFormat:@"%@-%@",name,tkmodel.name];
                        [weakSelf refreshingData];
                        return;
                    }
                }
            }];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(tableView == self.rztableview){
        return kwt(60);
    } else {
        return 0;
    }
}
//- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//    if(tableView == self.rztableview){
//        
//        UIView * bkview = [UIView new];
//        bkview.clipsToBounds = YES;
//        UILabel * temp5 = [DTKTool labelWithText:@"更有更多了～" andFont:kFont(14) andTextColor:KcolorHex(@"#787A79")];
//        [bkview addSubview:temp5];
//        [temp5 mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.center.offset(0);
//            
//        }];
//        
//        return bkview;
//    }
//    return [UIView new];
//}
//-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    if(tableView == self.rztableview){
//        if(self.modelArray.count > 0){
//            return kwt(50);
//        }
//    }
//    return 0;
//}


- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(tableView == self.rztableview){
        
        return  self.modelArray.count;
    } else {
        return 1;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if(tableView == self.rztableview){
        return self.modelArray[indexPath.row].CellH;
        
    } else {
        return self.model.postNameViewH + kwt(280);
    }
    
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    MJWeakSelf
    
    if(tableView == self.rztableview){
        AppendLogsableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AppendLogsableViewCell"];
        if (cell == nil) {
            cell = [[AppendLogsableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AppendLogsableViewCell"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.modelArray[indexPath.row];
        cell.openReloadBlock = ^{
            [weakSelf.rztableview reloadData];
        };
        return cell ;
        
    } else {
        PersonnelDetailsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"PersonnelDetailsTableViewCell"];
        if (cell == nil) {
            cell = [[PersonnelDetailsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PersonnelDetailsTableViewCell"];
        }
        cell.model = self.model;
        cell.openRWBlock = ^(int state) {
            UserQuestViewController * vc = [UserQuestViewController new];
            vc.state = state;
            vc.user = weakSelf.model.userId;
            vc.userId = weakSelf.model.userId;
            vc.userName = weakSelf.model.realName;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell ;
        
    }
}


- (void)openTime{
    MJWeakSelf
    [TimeFrameShowView CZshowviewWithTitle:@"选择时间" andStartTime:self.startTime andEndTime:self.endTime andRightBlock:^(NSString * _Nonnull StartTime, NSString * _Nonnull EndTime) {
        weakSelf.endTime = EndTime;
        weakSelf.startTime = StartTime;
        self.modelArray = [NSMutableArray array];
        [weakSelf loadRZNewData];
    } andCZBlock:^{
        weakSelf.endTime = nil;
        weakSelf.startTime = nil;
        self.modelArray = [NSMutableArray array];
        [weakSelf loadRZNewData];
    }];
}

- (void)dealloc{
    [[SYAudio shareAudio] audioStop];
}
@end
